import 'dart:convert';

import 'package:clean_app/asset/color.dart';
import 'package:clean_app/asset/modal.dart';
import 'package:clean_app/asset/storage.dart';
import 'package:clean_app/asset/textstyle.dart';
import 'package:clean_app/interface/mid_interface.dart';
import 'package:flutter/material.dart';
import 'package:uuid/uuid.dart';
import 'package:flutter_image_compress/flutter_image_compress.dart';
import 'package:path_provider/path_provider.dart';
import 'dart:io';
import 'package:path/path.dart' as path;

class DraftsPage extends StatefulWidget {
  @override
  _DraftsPageState createState() => _DraftsPageState();
}

class _DraftsPageState extends State<DraftsPage> {
  List<dynamic> drafts = [];
  List<bool> selected = [];
  bool isLoading = true;

  @override
  void initState() {
    super.initState();
    _loadDrafts();
  }

  _loadDrafts() async {
    try {
      String draftsStr = await getStorage(key: "drafts", initData: "[]");
      setState(() {
        drafts = json.decode(draftsStr);
        selected = List.generate(drafts.length, (index) => false);
        isLoading = false;
      });
    } catch (e) {
      setState(() {
        isLoading = false;
      });
      Toast.showInCenter(text: "加载草稿失败: $e", context: context);
    }
  }

  _uploadDraft(int index) async {
    try {
      final draft = drafts[index];

      LoadingDialog.show(context);

      // 获取上传URL
      var res = await UploadApi().getPresignedUrl();
      var presignedUrl = res["data"]["url"];

      // 压缩图片
      var compressedImage = await FlutterImageCompress.compressWithFile(
        draft["image_path"],
        minWidth: 1000,
        minHeight: 1000,
        quality: 20,
      );

      // 保存压缩后的图片到临时文件
      var tempDir = await getTemporaryDirectory();
      var file =
          await File('${tempDir.path}/image_${DateTime.now().millisecond}.jpg')
              .create();
      file.writeAsBytesSync(compressedImage!);

      // 上传图片
      await UploadApi().uploadWithPresignedUrl(
        file.path,
        presignedUrl,
        (progress_1, progress_2) {},
      );

      var imgUrl = presignedUrl.split("?")[0];

      // 提交标注数据
      await TaskApi().postSubmissions({
        "submissions": [
          {
            "client_id": draft["client_id"] ?? Uuid().v4(),
            "image_url": imgUrl,
            "score": 0,
            "tags": [],
            "task_context": draft["task_context"],
            "annotations": draft["annotations"],
          }
        ],
      });

      // 上传成功后从草稿中移除
      setState(() {
        drafts.removeAt(index);
        selected.removeAt(index);
      });

      // 更新本地存储
      await setStorage(key: "drafts", value: json.encode(drafts));

      LoadingDialog.dismiss(context);
      Toast.showInCenter(text: "上传完成", context: context);
    } catch (e) {
      LoadingDialog.dismiss(context);
      Toast.showInCenter(text: "上传失败: $e", context: context);
    }
  }

  _batchUpload() async {
    List<int> selectedIndexes = [];
    for (int i = 0; i < selected.length; i++) {
      if (selected[i]) {
        selectedIndexes.add(i);
      }
    }

    if (selectedIndexes.isEmpty) {
      Toast.showInCenter(text: "请先选择要上传的草稿", context: context);
      return;
    }

    // 反向遍历以避免索引变化问题
    for (int i = selectedIndexes.length - 1; i >= 0; i--) {
      int index = selectedIndexes[i];
      await _uploadDraft(index);
    }

    Toast.showInCenter(text: "批量上传完成", context: context);
  }

  _deleteDraft(int index) async {
    showModal(
        context: context,
        title: "请确认",
        cont: "请确认是否删除此草稿？",
        confirm: () async {
          setState(() {
            drafts.removeAt(index);
            selected.removeAt(index);
          });
          await setStorage(key: "drafts", value: json.encode(drafts));
          Toast.showInCenter(text: "草稿已删除", context: context);
        });
  }

  _deleteSelected() async {
    if (selected.where((element) => element).isEmpty) {
      Toast.showInCenter(text: "请先选择要删除的草稿", context: context);
      return;
    }

    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: Text("确认删除"),
          content: Text("确定要删除选中的草稿吗？"),
          actions: [
            TextButton(
              onPressed: () {
                Navigator.of(context).pop();
              },
              child: Text("取消"),
            ),
            TextButton(
              onPressed: () {
                Navigator.of(context).pop();
                _performDeleteSelected();
              },
              child: Text("确定"),
            ),
          ],
        );
      },
    );
  }

  _performDeleteSelected() {
    // 反向遍历以避免索引变化问题
    for (int i = selected.length - 1; i >= 0; i--) {
      if (selected[i]) {
        drafts.removeAt(i);
        selected.removeAt(i);
      }
    }

    // 更新本地存储
    setStorage(key: "drafts", value: json.encode(drafts));

    setState(() {});
    Toast.showInCenter(text: "选中的草稿已删除", context: context);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: os_back,
      appBar: AppBar(
        backgroundColor: os_back,
        centerTitle: true,
        title: Text(
          "草稿箱 (${drafts.length})",
          style: XSTextStyle(
            context: context,
            color: os_black,
            fontSize: 16,
            fontWeight: FontWeight.bold,
          ),
        ),
        actions: [
          if (drafts.isNotEmpty)
            TextButton(
              onPressed: _batchUpload,
              child: Text(
                "批量上传",
                style: XSTextStyle(
                  context: context,
                  color: os_color,
                  fontSize: 16,
                  fontWeight: FontWeight.bold,
                ),
              ),
            ),
        ],
        leading: IconButton(
          onPressed: () {
            Navigator.of(context).pop();
          },
          icon: Icon(
            Icons.chevron_left,
            size: 28,
          ),
        ),
      ),
      body: isLoading
          ? Center(child: CircularProgressIndicator())
          : drafts.isEmpty
              ? Center(
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Icon(Icons.inbox, size: 64, color: Colors.grey),
                      SizedBox(height: 10),
                      Text("暂无草稿",
                          style: TextStyle(fontSize: 16, color: Colors.grey)),
                      SizedBox(height: 150),
                    ],
                  ),
                )
              : Column(
                  children: [
                    Expanded(
                      child: ListView.builder(
                        itemCount: drafts.length,
                        itemBuilder: (context, index) {
                          try {
                            final draft = drafts[index];
                            return DraftItem(
                              draft: draft,
                              isSelected: selected[index],
                              onSelect: () {
                                setState(() {
                                  selected[index] = !selected[index];
                                });
                              },
                              onUpload: () => _uploadDraft(index),
                              onDelete: () => _deleteDraft(index),
                            );
                          } catch (_) {
                            return Container();
                          }
                        },
                      ),
                    ),
                  ],
                ),
    );
  }
}

class DraftItem extends StatelessWidget {
  final dynamic draft;
  final bool isSelected;
  final VoidCallback onSelect;
  final VoidCallback onUpload;
  final VoidCallback onDelete;

  const DraftItem({
    Key? key,
    required this.draft,
    required this.isSelected,
    required this.onSelect,
    required this.onUpload,
    required this.onDelete,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    final fileName = draft["image_path"] != null
        ? path.basename(draft["image_path"])
        : "未知文件";

    final timestamp = draft["timestamp"] != null
        ? DateTime.fromMillisecondsSinceEpoch(draft["timestamp"])
        : DateTime.now();

    final annotationsCount = draft["annotations"]?.length ?? 0;

    return AnimatedContainer(
      margin: EdgeInsets.symmetric(horizontal: 16, vertical: 8),
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(15),
        color: Colors.white,
        border: Border.all(
          color: isSelected ? os_color : os_white,
          width: 3,
        ),
      ),
      duration: Duration(milliseconds: 200),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 顶部选择区域
          ListTile(
            contentPadding:
                EdgeInsets.only(left: 16, right: 16, top: 5, bottom: 5),
            leading: GestureDetector(
              onTap: onSelect,
              child: Icon(
                isSelected ? Icons.check_box : Icons.check_box_outline_blank,
                color: isSelected ? os_color : Colors.grey,
              ),
            ),
            title: Text(
              fileName,
              maxLines: 1,
              overflow: TextOverflow.ellipsis,
              style: TextStyle(fontWeight: FontWeight.bold),
            ),
            subtitle: Text(
              "${timestamp.toString().split('.').first}  标注: $annotationsCount 项",
              style: XSTextStyle(
                context: context,
                color: os_deep_grey,
                fontSize: 14,
                fontWeight: FontWeight.normal,
              ),
            ),
            trailing: Row(
              mainAxisSize: MainAxisSize.min,
              children: [
                IconButton(
                  icon: Icon(Icons.upload, color: os_color),
                  onPressed: onUpload,
                ),
                IconButton(
                  icon: Icon(Icons.delete, color: Colors.red),
                  onPressed: onDelete,
                ),
              ],
            ),
          ),
          Container(
            margin: EdgeInsets.only(left: 15, right: 15, top: 0, bottom: 0),
            child: ClipRRect(
              borderRadius: BorderRadius.circular(10),
              child: Image.file(
                File(draft["image_path"]),
              ),
            ),
          ),
          // 任务上下文标签
          if (draft["task_context"] != null && draft["task_context"].isNotEmpty)
            Container(
              padding: EdgeInsets.symmetric(horizontal: 16, vertical: 15),
              child: Wrap(
                spacing: 8,
                runSpacing: 4,
                children: (draft["task_context"] as List)
                    .map((tag) => Container(
                          padding:
                              EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                          decoration: BoxDecoration(
                            color: os_color.withOpacity(0.1),
                            borderRadius: BorderRadius.circular(4),
                          ),
                          child: Text(
                            tag,
                            style: TextStyle(
                              color: os_color,
                              fontSize: 12,
                            ),
                          ),
                        ))
                    .toList(),
              ),
            ),
        ],
      ),
    );
  }
}
